<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" v-model="listQuery" class="search" size="mini">
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款单号">
              <el-input
                v-model="listQuery.name"
                placeholder="请输入付款单号"
                clearable
                @keyup.enter.native="handleFilter"
              ></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.supplier"
                placeholder="收款单位"
                clearable
                filterable
              >
                <el-option
                  v-for="item in suppliers"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-select
                v-model="listQuery.user"
                placeholder="付款人"
                clearable
              >
                <el-option
                  v-for="item in users"
                  :key="item.id"
                  :label="item.real_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleBatchDelete"
                >批量删除</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="付款时间">
              <el-select
                v-model="date_type"
                placeholder="请选择"
                @change="selectChange"
                clearable
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="">
              <el-date-picker
                v-model="listQuery.search_date"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click.native="handleFilter"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 上部 -->
      <el-table
        :data="datas"
        border
        stripe
        v-loading="listLoading"
        highlight-current-row
        style="width: 100%"
        size="mini"
        max-height="580"
        @selection-change="handleSelectionChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="expand" width="30">
          <template slot-scope="props">
            <div style="padding-left: 60px; width: 80%">
              <el-tabs v-model="activeItem">
                <el-tab-pane label="付款明细" name="1">
                  <el-table
                    :data="props.row.details"
                    border
                    stripe
                    size="mini"
                    highlight-current-row
                    style="width: 90%"
                  >
                    <el-table-column type="index" width="50" align="center" />
                    <el-table-column
                      prop="pay_order_code"
                      label="付款单号"
                      width="140"
                    />
                    <el-table-column
                      property="pay_order_pay_time"
                      label="付款日期"
                      width="120"
                    />
                    <el-table-column
                      property="pay_amount"
                      label="付款金额"
                      width="120"
                    />
                    <el-table-column
                      property="pay_order_account_name"
                      label="付款账号"
                      width="120"
                    />
                    <el-table-column property="entry_code" label="单据编号" />
                    <el-table-column property="flag_name" label="单据类型" />
                    <el-table-column property="remark" label="说明" />
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" align="center"> </el-table-column>

        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          :align="column.align"
          :width="column.width ? column.width : ''"
        >
          <template slot-scope="scope">
            <div v-if="column.key == 'code'">
              <el-link type="primary" @click="handleEdit(scope)" size="mini">{{
                scope.row[column.key]
              }}</el-link>
            </div>
            <div v-else>
              {{ dataFormatter(column.key, scope.row[column.key]) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="120px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getTitle"
      width="85%"
      top="10px"
      :close-on-click-modal="false"
    >
      <el-row style="margin-bottom: 10px; margin-top: -30px">
        <el-col :span="12" :offset="1">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="form.entry_code != null"
              @click="handleSave(false)"
              >保存</el-button
            >
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="form.entry_code != null"
              @click="handleSave(true)"
              >保存并新增</el-button
            >
            <el-button
              type="danger"
              size="small"
              plain
              @click="dialogVisible = false"
              >关闭</el-button
            >
          </el-button-group>
        </el-col>
      </el-row>
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="padding: 0 20px"
        status-icon
        size="mini"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款单编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="收款单编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款账号" prop="account">
              <el-select v-model="form.account" placeholder="付款账号">
                <el-option
                  v-for="item in accounts"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款时间" prop="pay_time">
              <el-date-picker
                v-model="form.pay_time"
                type="date"
                placeholder="付款时间"
                clearable
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收款单位" prop="supplier">
              <el-select
                v-model="form.supplier"
                placeholder="收款单位"
                clearable
                filterable
              >
                <el-option
                  v-for="item in suppliers"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款人" prop="user">
              <el-select v-model="form.user" placeholder="付款人" clearable>
                <el-option
                  v-for="item in users"
                  :label="item.real_name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="应付款金额" prop="payable">
              <el-input
                v-model="form.payable"
                placeholder="应付款金额"
                clearable
                disabled
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="本次付款金额" prop="pay_amount">
              <el-input
                v-model="form.pay_amount"
                placeholder="本次付款金额"
                clearable
                disabled
                @input="
                  form.pay_amount = form.pay_amount.replace(/[^\d|.]/g, '')
                "
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="优惠金额" prop="discount_amount">
              <el-input
                v-model="form.discount_amount"
                placeholder="优惠金额"
                clearable
                disabled
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际付款金额" prop="actual_amount">
              <el-input
                v-model="form.actual_amount"
                placeholder="实际付款金额"
                clearable
                @input="discountInput"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="16">
            <el-form-item label="说明" prop="remark">
              <el-input v-model="form.remark" placeholder="说明"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="bottom">
          <el-tabs v-model="activeName">
            <el-tab-pane label="付款明细" name="first">
              <el-row>
                <el-col :span="12">
                  <el-button-group>
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      v-if="form.entry_code == null"
                      @click="handleSelectEntry"
                      >选择入库单</el-button
                    >
                    <el-button
                      plain
                      type="primary"
                      size="small"
                      v-if="form.entry_code == null"
                      @click="deleteItem"
                      >删除</el-button
                    >
                  </el-button-group>
                </el-col>
              </el-row>
              <el-table
                :data="form.details"
                border
                highlight-current-row
                style="width: 100%"
                size="mini"
                id="detail"
                @selection-change="handleItemChange"
              >
                <el-table-column type="selection" width="40"></el-table-column>
                <el-table-column label="入库单编号" align="center" width="180">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.entry_code"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="订单时间" align="center" width="140">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.entry_warehouse_time"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="单据金额" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.entry_total_amount"
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="已付款金额" align="center" width="120">
                  <template slot-scope="scope">
                    <el-form-item label-width="0">
                      <el-input
                        v-model="scope.row.entry_amount"
                        placeholder=""
                        disabled
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="本次付款金额"
                  align="center"
                  width="160"
                >
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.pay_amount'"
                      label-width="0"
                      :rules="formRules.pay_amount"
                    >
                      <el-input
                        v-model="scope.row.pay_amount"
                        placeholder=""
                        clearable
                        size="small"
                        @input="calcAmounts"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="备注说明" align="center">
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'details.' + scope.$index + '.remark'"
                      label-width="0"
                    >
                      <el-input
                        v-model="scope.row.remark"
                        placeholder=""
                        clearable
                        size="small"
                      ></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      title="选择采购入库单"
      :visible.sync="dlgEntryVisible"
      top="5vh"
      width="80%"
    >
      <Entry
        :dlgEntryVisible.sync="dlgEntryVisible"
        @selections="getSelections"
        ref="entry"
      ></Entry>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import Entry from "@/views/components/Entry";

import {
  getPurchasePayOrders,
  addPurchasePayOrder,
  updatePurchasePayOrder,
  delPurchasePayOrder,
  delPurchasePayOrders,
  getPurchasePayMaxCode,
  delPurchasePayOrderDetails,
} from "@/api/purchase";
import { getSupplierList } from "@/api/base";
import { getUserList } from "@/api/user";
import { getAccountList } from "@/api/finance";
import { getCurrentDate } from "@/utils/datetime";

const defaultForm = {
  id: null,
  code: "",
  account: null,
  pay_time: getCurrentDate(),
  supplier: null,
  user: null,
  payable: 0,
  pay_amount: 0,
  discount_amount: 0,
  actual_amount: 0,
  oper: null,
  remark: "",
  flag: 0,
  details: [],
};
const defaultItemForm = {
  entry: null,
  entry_code: null,
  entry_warehouse_time: null,
  entry_total_amount: null,
  entry_amount: null,
  pay_amount: 0,
  remark: "",
};

export default {
  name: "PurchasePayOrder",
  data() {
    return {
      form: Object.assign({}, defaultForm),
      itemForm: Object.assign({}, defaultItemForm),
      current_row: {},
      formRules: {
        code: [
          {
            type: "string",
            required: true,
            message: "请输入付款单编号",
            trigger: "blur",
          },
        ],
        pay_time: [
          {
            required: true,
            message: "请输入付款时间",
            trigger: "blur",
          },
        ],
        supplier: [
          {
            required: true,
            message: "请选择收款单位",
            trigger: ["blur", "change"],
          },
        ],
        account: [
          {
            required: true,
            message: "请选择付款账户",
            trigger: ["blur", "change"],
          },
        ],
        entry: [
          {
            required: true,
            message: "请选择入库单",
            trigger: ["blur", "change"],
          },
        ],
        pay_amount: [
          {
            required: true,
            message: "请输入本次付款金额",
            trigger: "blur",
          },
        ],
      },

      tableColumns: [
        {
          key: "code",
          title: "付款单编号",
          align: "left",
          width: "140",
        },
        {
          key: "pay_time",
          title: "付款时间",
          align: "center",
          width: "100",
        },
        {
          key: "supplier_name",
          title: "收款单位",
          width: "160",
        },
        {
          key: "user_name",
          title: "付款人",
          align: "center",
          width: "80",
        },
        {
          key: "payable",
          title: "应付款金额",
          align: "center",
          width: "120",
        },
        {
          key: "pay_amount",
          title: "本次付款金额",
          align: "center",
          width: "120",
        },
        {
          key: "discount_amount",
          title: "优惠金额",
          align: "center",
          width: "120",
        },
        {
          key: "actual_amount",
          title: "实际付款",
          align: "center",
          width: "90",
        },
        {
          key: "account_name",
          title: "付款账号",
          align: "center",
          width: "100",
        },
        {
          key: "flag_name",
          title: "支付方式",
          align: "center",
          width: "100",
        },
        {
          key: "oper_name",
          title: "操作人",
          align: "center",
          width: "100",
        },
        {
          key: "remark",
          title: "说明",
          align: "center",
        },
      ],
      itemTableColumns: [
        {
          key: "pay_order_code",
          title: "收款单编号",
          align: "left",
          width: "140",
        },
        {
          key: "pay_time",
          title: "收款时间",
          align: "left",
          width: "100",
        },

        {
          key: "pay_amount",
          title: "付款金额",
          width: "140",
        },
        {
          key: "pay_order_account_name",
          title: "付款账号",
          width: "80",
          align: "center",
        },
        {
          key: "entry_code",
          title: "入库单号",
          width: "120",
          align: "center",
        },
        {
          key: "remark",
          title: "备注",
          width: "140",
        },
      ],
      title: "采购付款单",
      dialogVisible: false,
      dlgEntryVisible: false,

      activeName: "first",
      activeItem: "1",

      dialogType: "new",
      datas: [],
      itemDatas: [],
      suppliers: [],
      users: [],
      entries: [],

      accounts: [],
      selections: [],
      itemSels: [],
      date_type: 3,

      selectedKeys: [],
      props: {
        expandTrigger: "hover",
        value: "id",
        label: "name",
        children: "children",
      },
      //树形
      defaultProps: {
        children: "children",
        label: "name",
      },

      status_items: [
        { id: 0, name: "等待付款" },
        { id: 1, name: "完全付款" },
      ],

      options: [
        { value: 0, label: "当天" },
        { value: 1, label: "本周" },
        { value: 2, label: "本月" },
        { value: 3, label: "最近一月" },
        { value: 4, label: "本年" },
      ],

      total: 0,
      listLoading: true,
      finished: false,

      listQuery: {
        name: "",
        supplier: null,
        user: null,
        search_date: [
          moment().add(-30, "days").format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Entry,
  },
  created() {
    this.getPayOrderList();
    this.getSuppliers();
    this.getUserCodeList();
    this.getAccountCodeList();
  },
  methods: {
    handleSelectEntry() {
      if (this.form.supplier == null) {
        this.$message({
          type: "success",
          message: "请选择收款单位!",
        });
        return;
      }
      this.dlgEntryVisible = true;
      this.$nextTick(() => {
        this.$refs.entry.init_data(this.form.supplier);
      });
    },
    //选择入库单
    getSelections(val) {
      for (const obj of val) {
        let row = Object.assign({}, defaultItemForm);
        row.entry = obj.id;
        row.entry_code = obj.code;
        row.entry_warehouse_time = obj.warehouse_time;
        row.entry_total_amount = obj.total_amount.toFixed(2);
        row.entry_amount = obj.amount.toFixed(2);
        row.pay_amount = obj.nopay_amount.toFixed(2);
        this.form.details.push(row);
      }

      this.calcAmounts();
    },
    //时间查询
    selectChange(val) {
      if (val == 0) {
        this.listQuery.search_date = [
          moment().format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ];
      } else if (val == 1) {
        this.listQuery.search_date = [
          moment().startOf("week").format("YYYY-MM-DD"),
          moment().endOf("week").format("YYYY-MM-DD"),
        ];
      } else if (val == 2) {
        this.listQuery.search_date = [
          moment().startOf("month").format("YYYY-MM-DD"),
          moment().endOf("month").format("YYYY-MM-DD"),
        ];
      } else if (val == 3) {
        this.listQuery.search_date = [
          moment().add(-30, "days").format("YYYY-MM-DD"),
          moment().format("YYYY-MM-DD"),
        ];
      } else if (val == 4) {
        this.listQuery.search_date = [
          moment().startOf("year").format("YYYY-MM-DD"),
          moment().endOf("year").format("YYYY-MM-DD"),
        ];
      }
      this.getPayOrderList();
    },

    discountInput() {
      this.form.actual_amount = this.form.actual_amount.replace(
        /[^\d|.]/g,
        ""
      );
      
      let dis_amount = this.form.pay_amount - this.form.actual_amount
      // dis_amount = dis_amount && dis_amount.toFixed(2);
      this.form.discount_amount = dis_amount.toFixed(2);
       
    },

    calcAmounts() {
      let sum = 0;
      let pay_amount = 0;

      //去重
      var hash = {};
      const entries = this.form.details.reduce(function (item, next) {
        hash[next.entry_code]
          ? ""
          : (hash[next.entry_code] = true && item.push(next));
        return item;
      }, []);

      for (const row of entries) {
        sum += parseFloat(row.entry_total_amount);
      }

      for (const row of this.form.details) {
        pay_amount += parseFloat(row.pay_amount);
      }

      this.form.payable = sum.toFixed(2);
      this.form.pay_amount = pay_amount.toFixed(2);
      this.form.discount_amount = 0;
      this.form.actual_amount =
        this.form.pay_amount - this.form.discount_amount;
    },

    handleChange(row, val) {
      // let index = this.goodsList.findIndex((v) => v.id == val);
      // row.goods_name = "";
      // row.goods_cate_name = "";
      // row.goods_unit_name = "";
      // row.goods_specs = "";
      // row.price = "";
      // if (index != -1) {
      //   const goods = this.goodsList[index];
      //   row.goods_name = goods.name;
      //   row.goods_cate_name = goods.cate_name;
      //   row.goods_unit_name = goods.unit_name;
      //   row.goods_specs = goods.specs;
      //   row.price = goods.sale_price;
      // }
    },

    getPurOrderMaxCode() {
      getPurchasePayMaxCode().then((res) => {
        this.form.code = res.max_code;
      });
    },
    getAccountCodeList() {
      getAccountList().then((res) => {
        this.accounts = res;
      });
    },

    getUserCodeList() {
      getUserList().then((res) => {
        this.users = res;
      });
    },
    getSuppliers() {
      getSupplierList().then((res) => {
        this.suppliers = res;
      });
    },

    getPayOrderList() {
      this.listLoading = true;
      getPurchasePayOrders(this.listQuery)
        .then((res) => {
          this.datas = res;
          this.listLoading = false;
          this.finished = true;
        })
        .catch((error) => {
          this.$message.error("获取数据失败:" + error);
          this.listLoading = false;
          this.finished = true;
        });
    },

    handleSelectionChange(val) {
      this.selections = val.map((item) => item.id);
    },

    handleItemChange(val) {
      // this.itemSels = val.map((item) => item.id);
      this.itemSels = val;
    },

    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.datas = [];
      this.getPayOrderList();
    },

    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delPurchasePayOrder(row.id);

          const index = this.datas.findIndex((v) => v.id == row.id);
          this.datas.splice(index, 1);
          this.itemDatas = [];
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "fail",
            message: "删除失败:" + err,
          });
        });
    },

    //批量删除
    handleBatchDelete() {
      if (this.selections.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.selections,
          };
          const res = await delPurchasePayOrders(sel_ids);
          this.itemDatas = [];

          this.getPayOrderList();

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "success",
            message: "删除失败!" + err,
          });
        });
    },

    //批量删除
    deleteItem() {
      if (this.itemSels.length == 0) {
        this.$message.warning("请选择要删除记录");
        return;
      }
      this.$confirm("确定要删除选中记录吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const sel_ids = {
            select_ids: this.itemSels
              .filter((item) => {
                return item.id != undefined;
              })
              .map((item) => item.id),
          };

          if (sel_ids.select_ids.length > 0) {
            const res = await delPurchasePayOrderDetails(sel_ids);
          }

          this.form.details = this.form.details.filter((item) => {
            return !this.itemSels.includes(item);
          });

          if (this.current_row != null) {
            this.current_row.details = this.current_row.details.filter(
              (item) => {
                return !this.itemSels.includes(item);
              }
            );
          }

          if (sel_ids.select_ids.length > 0) {
            this.calcAmounts();
            if (this.dialogType == "edit") {
              updatePurchasePayOrder(this.form).then((res) => {
                console.log(res);
              });
            }
          }
          
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          this.$message({
            type: "danger",
            message: "删除失败!" + err,
          });
        });
    },

    addItem() {
      let itemForm = Object.assign({}, defaultItemForm);
      this.form.details.push(itemForm);
    },

    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);
      this.form.details = [];
      this.getPurOrderMaxCode();

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改
    handleEdit(scope) {
      this.current_row = scope.row;
      this.form = JSON.parse(JSON.stringify(scope.row));
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        // this.selectedKeys = getParentsPath(key, this.stations);
        this.$refs.formRef.clearValidate();
      });
    },

    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        let res = null;
        if (this.form.oper == null || this.form.oper == undefined) {
          this.form.oper = this.uid;
        }
        if (isEdit) {
          console.log(this.form);
          res = await updatePurchasePayOrder(this.form);
        } else {
          res = await addPurchasePayOrder(this.form);
        }

        this.getPayOrderList();

        const { code, pay_time, supplier_name, user_name, pay_amount } = res;

        if (flag) {
          this.form = Object.assign({}, defaultForm);
          this.dialogType = "new";
          this.getPurOrderMaxCode();
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>付款单编号: ${code}</div>
              <div>付款时间: ${pay_time}</div>
              <div>收款单位: ${supplier_name}</div>
              <div>付款人: ${user_name}</div>
              <div>付款金额: ${pay_amount}</div>
            `,
          type: "success",
        });
      });
    },

    dataFormatter(column, cellValue) {
      if (
        column == "payable" ||
        column == "pay_amount" ||
        column == "discount_amount" ||
        column == "actual_amount"
      ) {
        return (
          (cellValue || cellValue === 0) && parseFloat(cellValue).toFixed(2)
        );
      } else {
        return cellValue;
      }
    },

    //合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 2) {
          sums[index] = "合计";
          return;
        }
        if (
          column.property === "payable" ||
          column.property === "pay_amount" ||
          column.property === "discount_amount" ||
          column.property === "actual_amount"
        ) {
          const values = data.map((item) => item[column.property]);
          sums[index] = values
            .reduce((prev, curr) => {
              return parseFloat(prev) + parseFloat(curr || 0);
            }, 0)
            .toFixed(2);
          sums[index] += " 元";
        } else {
          return;
        }
      });
      return sums;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .el-select,
  .el-cascader {
    width: 100%;
  }

  .dialog .el-form {
    margin-top: 20px;
  }
  .el-link {
    font-size: 12px;
  }
  .el-row {
    margin-left: 10px;
  }
}
</style>